<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="7">
                <el-row>
                    <div class="search-container">
                        <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams"
                            label-width="80px">
                            <el-form-item label="所属机构" style="width: 100%;" v-if="!userInfo.orgId" prop="orgId">
                                <select-org-tree :value="queryParams.orgId" @orgNodeClick="orgNodeClick" />
                            </el-form-item>
                            <el-form-item label="所属号别" prop="clinicIndexId">
                                <el-input v-model="queryParams.clinicIndexId" clearable placeholder="请输入所属号别"
                                    @keyup.enter.native="handleQuery" />
                            </el-form-item>

                            <el-form-item label="就诊星期" prop="dayOfWeek">
                                <el-select v-model="queryParams.dayOfWeek" class="width-120" clearable
                                    placeholder="请选择就诊星期">
                                    <el-option v-for="dict in dictDataMap['week_dict']" :key="dict.dictValue"
                                        :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="时间描述" prop="timeDesc">
                                <el-select v-model="queryParams.timeDesc" class="width-120" clearable
                                    placeholder="请选择时间描述">
                                    <el-option v-for="dict in dictDataMap['clinic_visit_schedule']"
                                        :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                            </el-form-item>

                            <div style="float: right" class="mr20">
                                <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                            </div>
                        </el-form>
                    </div>
                </el-row>

                <el-row>
                    <clinic-schedule-table ref="clinicScheduleTableRef"
                        @clinicScheduleTableChange="clinicScheduleTableChange" />
                </el-row>
            </el-col>
            <el-col :span="17" :xs="24">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="160px">
                    <el-row :gutter="40" class="mb8">
                        <el-col :span="10">
                            <el-form-item label="号表有效期限" prop="registryTimeScope">
                                <el-date-picker v-model="form.registryTimeScope" :disabled="isDisable"
                                    style="width: 100%;" :picker-options="pickerOptions" end-placeholder="结束日期"
                                    range-separator="至" start-placeholder="开始日期" type="daterange"
                                    value-format="YYYY-MM-DD">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="1">
                            <el-form-item label="">
                                <el-button :disabled="isDisable" type="primary" @click="submitForm">保存
                                </el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <el-table v-adaptive :data="clinicForRegistList" :border="true" highlight-current-row :stripe="true"
                    :header-cell-style="$headerCellStyle">
                    <!--                    <el-table-column type="selection" width="55" :align="'center'"/>-->
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="所属号别"
                        prop="clinicIndexName" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="就诊日期" prop="clinicDate"
                        width="180">
                        <template #default="scope">
                            <span>{{ $parseTime(scope.row.clinicDate, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="时间描述" prop="timeDesc">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['clinic_visit_schedule']"
                                :value="scope.row.timeDesc" />
                        </template>
                    </el-table-column>
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="限号数" prop="limitNum" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="限预约号数" prop="limitPreNum" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="当前号" prop="currentNum" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="当日已挂号数"
                        prop="currentRegisNum" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="已预约号数"
                        prop="currentPreNum" />
                    <!--                    <el-table-column :show-overflow-tooltip="true" :align="'center'" label="备注信息" prop="remark"/>-->
                    <el-table-column :align="'center'" class-name="small-padding fixed-width" label="操作">
                        <template #default="scope">
                            <!--                    <el-button-->
                            <!--                        -->
                            <!--                        type="success"-->
                            <!--                        icon="el-icon-edit"-->
                            <!--                        @click="handleUpdate(scope.row)"-->
                            <!--                        v-hasPerm="['base:clinicForRegist:edit']"-->
                            <!--                    >修改-->
                            <!--                    </el-button>-->
                            <el-button v-hasPerm="['base:clinicForRegist:remove']" type="danger"
                                @click="handleDelete(scope.row)"><template #icon>
                                    <i-ep-delete />
                                </template>删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList" />

            </el-col>
        </el-row>

        <!-- 添加或修改号表安排对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="500px">
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
    addClinicForRegist,
    delClinicForRegist,
    getClinicForRegist,
    selectPageClinicForRegist
} from "@/api/base/clinicForRegist";
import clinicScheduleTable from "@/views/base/clinicForRegist/clinicScheduleTable.vue";
import selectOrgTree from "@/components/SysOrgTree/selectOrgTree.vue";
import { useDictStoreHook } from "@/store/modules/dict";
import { useUserStoreHook } from "@/store/modules/user";

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
const dictDataMap = ref(dictStore.isTypeGetData('clinic_visit_schedule', 'week_dict'))
const clinicScheduleTableRef = ref()
const formRef = ref()
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 选中数组
const ids = ref<any>([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
const title = ref()
// 总条数
const total = ref(0)
// 号表安排表格数据
const clinicForRegistList = ref([])
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParamsRef = ref()
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 30,
    clinicIndexId: undefined,
    clinicDate: undefined,
    timeDesc: undefined,
    limitNum: undefined,
    limitPreNum: undefined,
    currentNum: undefined,
    currentRegisNum: undefined,
    currentPreNum: undefined,
    dayOfWeek: undefined,
    orgId: undefined,
    clinicScheduleList: []
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
    registryTimeScope: [
        { required: true, message: "号表有效期限不能为空", trigger: "blur" }
    ],
})

// 时间选择、保存按钮是否禁用
const isDisable = ref(true)
// 时间禁用范围
const pickerOptions = ref({
    disabledDate(time) {
        return time.getTime() < Date.now() - 8.64e7;
    },
})
// 左侧选中列表数组
const clinicScheduleList = ref([])
if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId
} else {
    // getTreeSelect()
}

/** 左侧列表勾选事件 */
function clinicScheduleTableChange(obj) {
    isDisable.value = obj.length <= 0;
    clinicScheduleList.value = obj
    queryParams.value.clinicScheduleList = clinicScheduleList.value
    getList()
}
/** 查询号表安排列表 */
function getList() {
    selectPageClinicForRegist(queryParams.value).then((response: any) => {
        clinicForRegistList.value = response.rows;
        total.value = response.total;
    });
}
/** 查询机构下拉树结构 */
// function getTreeSelect(response) {
//     if (response) {
//         queryParams.value.orgId = response.data[0].orgId
//     }
// }
// 机构树点击事件
function orgNodeClick(data, _e) {
    queryParams.value.orgId = data.orgId
    if (queryParams.value.orgId) {
        // getDeptTree()
        // getList()
    }
}
// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        clinicForRegistId: undefined,
        clinicIndexId: undefined,
        clinicDate: undefined,
        timeDesc: undefined,
        limitNum: undefined,
        limitPreNum: undefined,
        currentNum: undefined,
        currentRegisNum: undefined,
        currentPreNum: undefined,
        orgId: queryParams.orgId,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
    };
}
/** 搜索按钮操作 */
function handleQuery() {
    if (!queryParams.value.orgId) {
        return ElMessage.error("请先选择左侧所属机构后查询")
    }
    clinicScheduleTableRef.value.getList(queryParams)
    // queryParams.pageNum = 1;
    // getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.clinicForRegistId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加号表安排";
}
/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const clinicForRegistId = row.clinicForRegistId || ids.value
    getClinicForRegist(clinicForRegistId).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改号表安排";
    });
}
/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            form.value.clinicScheduleList = clinicScheduleList.value
            if (form.value.registryTimeScope.length > 0) {
                form.value.orgId = queryParams.value.orgId
                form.value.startDate = form.value.registryTimeScope[0] + " 00:00:00"
                form.value.stopDate = form.value.registryTimeScope[1] + " 23:59:59"
            }
            ElMessageBox.confirm('确认要保存号表排班信息吗？',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                saveInfo()
            }).catch(() => {
            })
        }
    });
}
/** 保存操作 */
function saveInfo() {
    addClinicForRegist(form.value).then(_res => {
        getList();
        ElMessage.success("保存成功");
    })
}
/** 删除按钮操作 */
function handleDelete(row) {
    const clinicForRegistIds = row.clinicForRegistId || ids.value;
    ElMessageBox.confirm('是否确认删除号表安排编号为"' + clinicForRegistIds + '"的数据项？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        delClinicForRegist(clinicForRegistIds).then(() => {
            getList();
            ElMessage.success("删除成功")
        })
    }).catch(() => {
    })
}
/** 导出按钮操作 */
function handleExport() {
    // download('base/clinicForRegist/export', {
    //     ...queryParams
    // }, `clinicForRegist_${new Date().getTime()}.xlsx`)
}


</script>
<script lang="ts">
export default {
    name: "ClinicForRegist"
}
</script>
